package com.fintech.pangu.generator.util;

import com.fintech.pangu.exception.GeneratorException;
import com.fintech.pangu.generator.constant.DBConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JDBCUtil {

    private static Logger logger = LoggerFactory.getLogger(JDBCUtil.class);

    private Connection conn = null;
    private PreparedStatement statement = null;
    private ResultSet resultSet = null;
    private int currentPage;
    private int pageSize;
    private int total;

    public static JDBCUtil instance(String url, String userName, String password){
        JDBCUtil dataSource = null;
        try {
            Class.forName(DBConstant.DB_DRIVER_NAME);
            dataSource = new JDBCUtil();
            dataSource.conn = DriverManager.getConnection(url, userName, password);
        }catch (Exception se){
            logger.error("初始化JDBC出现错误：{}",se);
            GeneratorException.GENERATOR_DATASOURCE_EXCEPTION.throwException();
        }
        return dataSource;
    }



    public ResultSet executeSQL(String sql, String...params){
        try {
            statement = conn.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                statement.setString(i + 1, params[i]);
            }
            resultSet = statement.executeQuery();
        }catch (SQLException se){
            logger.error("JDBC执行sql，设置参数错误：{}",se);
            GeneratorException.GENERATOR_DATASOURCE_EXCEPTION.throwException();
        }
        return resultSet;
    }

    public ResultSet executeSQL(String sql,int currentPage, int pageSize, String...params){
        try {
            String upperSql = sql.toUpperCase();
            int start = upperSql.indexOf(" ") + 1;
            int end = upperSql.indexOf("FROM");
            String subStr = upperSql.substring(start, end);
            upperSql = upperSql.replace(subStr, " COUNT(1) AS TOTAL ");
            ResultSet resultSet = executeSQL(upperSql, params);
            resultSet.next();
            total = resultSet.getInt("TOTAL");
            this.currentPage = currentPage;
            this.pageSize = pageSize;
            sql = setPageParam(sql, currentPage, pageSize);
            resultSet = executeSQL(sql, params);
            return resultSet;
        }catch (Exception e) {
            logger.error("JDBC分页执行错误：{}",e);
        }
        return null;
    }

    private static String setPageParam(String sql,int currentPage, int pageSize){
        int start = (currentPage - 1) * pageSize;
        StringBuilder builder = new StringBuilder(sql);
        builder.append(" LIMIT ").append(start).append(",").append(pageSize);
        return builder.toString();
    }


    public void closeAll(){
        try {
            if(conn != null){
                conn.close();
            }
        } catch (SQLException e) {}
        try {
            if(statement != null){
                statement.close();
            }
        } catch (SQLException e) {}
        try {
            if(resultSet != null){
                resultSet.close();
            }
        } catch (SQLException e) {}
    }

    public int getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public int getTotal() {
        return total;
    }

    public void setTotal(int total) {
        this.total = total;
    }
}
